import 'package:flutter/material.dart';
import 'package:myapp1/service/wordtime.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

// 知识点: http请求(优化封装)、路由传参、EasyLoading的使用
// 官网: https://pub.dev/packages/http/install
// api: https://worldtimeapi.org/api/timezone/Asia/Hong_Kong


// 创建无状态Widget Loading
class Loading extends StatefulWidget {
  const Loading({super.key});

  @override
  State<Loading> createState() => _LoadingState();
}

class _LoadingState extends State<Loading> {
  String time = "加载中...";
  bool isrunning = false;
  void getData() async {
    if (isrunning == true) {
      return;
    }
    // 开始加载loading
    EasyLoading.show(status: 'loading...');
    isrunning = true;
    WordTime instance = WordTime(
        url: "Hong_Kong",
        location: "香港",
        flag: "hk.png",
    );
    String mytime = await instance.getTime();
    setState(() {
      time = mytime;
    });
    // 关闭加载框
    EasyLoading.dismiss();
    // 如果请求成功就跳转location页面
    if (instance.errno == 0) {
      // 路由传参
      Navigator.pushNamed(context, "/weather", arguments: {
        "location": instance.location,
        "flag": instance.flag,
        "time": instance.time,
        "isDaytime": instance.isDaytime
      });
      Future.delayed(Duration(seconds: 5), () {
          isrunning = false;
      });
    }
  }


  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      // appBar: AppBar(
      //   title: Text(
      //       "获取当前时间",
      //       style: TextStyle(
      //           fontSize: 20.0,
      //           color: Colors.white
      //       )
      //   ),
      //   centerTitle: true,
      //   backgroundColor: Colors.blue[800],
      //   // 设置返回按钮为白色
      //   iconTheme: IconThemeData(
      //       color: Colors.white
      //   ),
      // ),
      body: Center(
        // child: Text(
        //     time,
        //     style: TextStyle(
        //       fontSize: 20.0
        //     )
        // ),
      ),
    );
  }
}
